package com.auto.autoapp.task

import com.auto.autoapp.constants.Dy
import com.auto.autoapp.constants.VideoPageId
import com.auto.autoapp.model.Direction
import com.auto.autoapp.model.SceneType
import com.auto.autoapp.model.WatchVideoCommentSetting
import com.auto.autoapp.step.*
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.step.replyComment
import com.auto.autoapp.util.StringUtil
import com.auto.autoapp.util.addLog
import com.auto.autoapp.util.clickOrTap
import com.auto.autoapp.util.getNodeById
import com.ven.assists.AssistsCore
import com.ven.assists.AssistsCore.des
import com.ven.assists.AssistsCore.findById
import com.ven.assists.AssistsCore.getBoundsInScreen
import com.ven.assists.AssistsCore.setNodeText
import com.ven.assists.stepper.Step
import com.ven.assists.stepper.StepCollector
import com.ven.assists.stepper.StepImpl
import kotlinx.coroutines.delay

/**
 * 视频新评论监听并私信
 * 对指定视频进行监听，发现有新留言立即进行相关操作
 * 1. 前往抖音首页
 * 2. 获取抖音号，如果未登录则停止
 * 3. 前往搜索页面，根据配置进行搜索
 * 4. 在视频页面中查看评论，根据评论时间判断是否为新视频
 * 5. 根据关键字匹配评论，满足条件则点赞并回复
 * 6. 评论上滑查找，最多查找20条，无匹配则返回第3步
 */
class WatchVideoCommentTask : StepImpl() {

    private var setting = WatchVideoCommentSetting()
    private var searchedVideos = mutableListOf<String>() // 已搜索过的视频列表
    private var currentVideoIndex = 0
    private var maxCommentCount = 10
    private var maxDays = 10
    private var commentList = ArrayList<String>()

    override fun onImpl(collector: StepCollector) {
        // 读取配置
        setting = SpUtil.getWatchVideoCommentSetting()
        collector
            // Step 1: 前往抖音首页
            .next(1) {
                maxCommentCount = setting.maxCommentCount
                maxDays = setting.intervalDays
                addLog("开始视频评论监听任务")
                setting = SpUtil.getWatchVideoCommentSetting()
                searchedVideos.clear()
                currentVideoIndex = 0
                return@next toDyIndex(nextStep = 2)
            }

            // Step 2: 获取抖音号，检查登录状态
            .next(2) {
                val loginResult = checkLogin()
                if (loginResult.isSuccess) {
                    return@next Step.get(3)
                }
                return@next Step.none
            }
            //点击首页搜索，跳转搜索页面
            .next(3) {
                val searchNodeResult = Dy.ID_INDEX_SEARCH_NODE.clickOrTap()
                if (searchNodeResult.isFailure) {
                    addLog("未找到搜索入口，请重试")
                    AssistsCore.back()
                    delay(1000)
                    return@next Step.repeat
                }
                return@next Step.get(4)
            }

            // Step 4: 进入搜索页面，根据配置进行搜索
            .next(4) {
                val editText = AssistsCore.findById(Dy.ID_SEARCH_INPUT).firstOrNull()
                if (currentVideoIndex >= setting.videoList.size) {
                    addLog("视频错误，将重新开始")
                    currentVideoIndex = 0
                    return@next Step.repeat
                }
                val currentVideo = setting.videoList[currentVideoIndex]
                commentList.clear()
                maxCommentCount = 20

                addLog("进入搜索，关键词：${currentVideo}")
                delay(1500)
                if (editText != null) {
                    editText.setNodeText(currentVideo)
                    delay(2000)
                    Dy.SEARCH_BTN.clickOrTap()
                    addLog("已执行搜索视频：$currentVideo")
                    delay(3000)

                    addLog("scene:${getCurrentScene().getOrNull()}")
                    if (getCurrentScene().getOrNull() != SceneType.VIDEO_PAGE) {
                        addLog("无法跳转视频，请检查视频地址")
                        currentVideoIndex++
                        return@next Step.repeat
                    }
                    commentList.clear()
                    return@next Step.get(5)
                } else {
                    addLog("搜索输入框未找到")
                    return@next Step.get(1)
                }
            }
            // Step 5: 进入评论区，查看评论
            .next(5) {
                delay(2000) // 等待视频加载
                val commentBtnResult = clickCommentBtn()
                if (commentBtnResult.isFailure) {
                    addLog("无法打开评论区，返回搜索")
                    AssistsCore.back()
                    delay(1000)
                    return@next Step.get(1)
                }
                delay(1500)
                addLog("已进入评论区，开始检查评论")
                return@next Step.get(6)
            }

            // Step 6: 检查评论并进行匹配操作
            .next(6) {
                addLog("已检查评论数量：${commentList.size},最多检查：${maxCommentCount}")
                while (commentList.size < maxCommentCount) {
                    addLog("已检查评论数量：${commentList.size},最多检查：${maxCommentCount}")
                    val commentListResult = VideoPageId.ID_COMMENT_RV.getNodeById()
                    if (commentListResult.isFailure) {
                        addLog("评论列表失败，返回搜索页面")
                        val backResult = backToSearchPage()
                        if (backResult.isSuccess) {
                            return@next Step.get(4)
                        } else {
                            addLog("返回搜索页面失败,流程已终止")
                            return@next Step.none
                        }
                    }
                    val commentListNode = commentListResult.getOrNull()!!
                    val childCount = commentListNode.childCount
                    if (childCount == 0) {
                        return@next Step.get(7)
                    }
                    var hasNewComment = false
                    for (i in 0 until childCount) {
                        val cItem = commentListNode.getChild(i)
                        val replayNode = cItem.findById(Dy.ID_REPLY_COMMENT).firstOrNull()
                        val contentNode = cItem.findById(Dy.ID_COMMENT_CONTENT).firstOrNull()
                        var replayNodeVisible = replayNode?.isVisibleToUser == true
                        var contentNodeVisible = contentNode?.isVisibleToUser == true
                        var likeNode = cItem.findById(Dy.ID_COMMENT_LIKE).firstOrNull()
                        var likeNodeVisible = likeNode?.isVisibleToUser == true
                        val commentTimeNode = cItem.findById(VideoPageId.COMMENT_TIME).firstOrNull()
                        val commentTime =
                            StringUtil.toStandardDateTime(commentTimeNode?.text.toString())
                        val diffDays = StringUtil.diffDays(commentTime)

                        val content = contentNode?.text?.toString() ?: ""
                        if(!commentList.contains(content)){
                            hasNewComment = true
                        }


                        val fullVisible = likeNodeVisible && contentNodeVisible
                        if (!fullVisible) {
                            continue
                        }


                        addLog("评论时间为：$commentTime,与当前时间相差:${diffDays}天")
                        val timeValid = diffDays != null && diffDays <= maxDays

                        if (!commentList.contains(content)) {
                            commentList.add(content)
                        }
                        // 检查是否包含包含关键词
                        val includeMatch = setting.includeKeywords.isEmpty() ||
                                setting.includeKeywords.split(",").any { keyword ->
                                    content.contains(keyword.trim(), ignoreCase = true)
                                }
                        // 检查是否包含排除关键词
                        val excludeMatch = setting.excludeKeywords.isNotEmpty() &&
                                setting.excludeKeywords.split(",").any { keyword ->
                                    content.contains(keyword.trim(), ignoreCase = true)
                                }
                        if ((includeMatch || excludeMatch) && timeValid) {
                            addLog("关键字匹配成功")
                            val hasLiked = likeNode?.des()?.contains("已") == true
                            if (!hasLiked) {
                                likeNode?.clickOrTap()
                                delay(1200)
                            }
                            val replyContent = setting.replyList.random()
                            delay(2000)
                            replyComment(replyContent)
                            addLog("replyContent:$replyContent")

                        }
//                        addLog("replyNodeVisible:$replayNodeVisible,contentNodeVisible:$contentNodeVisible,likeNodeVisible:$likeNodeVisible")
//                        addLog("${replayNode?.des()}---${contentNode?.des()}---${contentNode?.text}--${likeNode?.des()}")

                    }

                    //评论数量没有变化，视为评论全部加在完毕
                    if(!hasNewComment){
                        addLog("已检索玩全部评论")
                        return@next Step.get(7)
                    }
                    delay(2000)
                    scroll(VideoPageId.ID_COMMENT_RV, Direction.B2T, to = 0.1f)
                    delay(1200)
                }
                return@next Step.get(7)
            }

            // Step 7: 返回搜索页面继续下一个视频
            .next(7) {
                val backResult = backToSearchPage()
                if (backResult.isSuccess) {
                    return@next Step.get(4)
                } else {
                    addLog("返回搜索页面失败,流程已终止")
                    return@next Step.none
                }

            }
    }

    /**
     * 获取评论时间
     */
    private fun getCommentTime(commentNode: Any): String {
        // 这里需要根据实际的UI结构来获取评论时间
        // 假设时间信息在评论节点的某个子节点中
        return "刚刚" // 简化处理，实际应用中需要解析具体时间
    }

    /**
     * 判断评论是否为较新的评论
     */
    private fun isNewComment(commentTime: String): Boolean {
        // 简化处理，可以根据实际需求调整时间判断逻辑
        // 例如：包含"刚刚"、"分钟前"、"小时前"等关键词认为是新评论
        val newKeywords = listOf("刚刚", "分钟前", "小时前", "今天")
        return newKeywords.any { commentTime.contains(it) }
    }

    /**
     * 滑动评论列表
     */
    private suspend fun scrollCommentList(): Result<Any> {
        val commentListResult = VideoPageId.ID_COMMENT_RV.getNodeById()
        if (commentListResult.isFailure) {
            return Result.failure(Exception("未找到评论列表"))
        }

        val commentList = commentListResult.getOrNull()!!
        val bounds = commentList.getBoundsInScreen()

        val centerX = bounds.centerX().toFloat()
        val startY = bounds.bottom - 100f
        val endY = bounds.top + 100f

        val result = AssistsCore.gesture(
            floatArrayOf(centerX, startY),
            floatArrayOf(centerX, endY),
            100,
            300
        )

        return if (result) {
            Result.success("success")
        } else {
            Result.failure(Exception("滑动失败"))
        }
    }
}